<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    align-center
    width="1200px"
    style="height: 800px;"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
      class="customer-form"
    >
       <fieldset>
        <legend>基本信息</legend>
        <el-form-item label-width="6em" label="姓名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label-width="6em" label="年龄" prop="age">
          <el-input v-model="formData.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label-width="6em" label="用户性别" prop="sex">
          <el-radio-group v-model="formData.sex">
            <el-radio
              v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label-width="6em" label="手机号码" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label-width="6em" label="贷款额度" prop="quota">
          <el-input v-model="formData.quota" placeholder="请输入贷款额度">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <!-- <el-form-item label-width="6em" label="客户类型" prop="customerType">
          <el-select
            v-model="formData.customerType"
            placeholder="请选择客户类型"
            style="width: 220px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.CUSTOMER_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label-width="6em" label="客户星级" prop="starRating">
          <el-select
            v-model="formData.starRating"
            placeholder="请选择客户星级"
            clearable
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.CUSTOMERSTARRATING)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </fieldset>

      <fieldset>
        <legend>跟进信息</legend>
        <!-- <el-form-item label-width="6em" label="跟进人" prop="followUp">
          <el-select
            v-model="formData.followUp"
            placeholder="请选择跟进人"
            clearable
            @change="handleChangeFollowUp"
            style="margin-right: 12px;"
          >
            <el-option
              v-for="item in followUpList"
              :key="item.id"
              :value="item.id"
              :label="item.username"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label-width="6em" label="跟进状态" prop="followUpStatus">
          <el-select
            v-model="formData.followUpStatus"
            placeholder="请选择跟进状态"
            style="width: 100%"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.FOLLOWUPSTATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label-width="6em" label="跟进次数" prop="followUpFrequency">
          <el-input-number
            v-model="formData.followUpFrequency"
            :min="0"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label-width="6em" label="跟进时间" prop="followTime">
          <el-date-picker
            v-model="formData.followTime"
            type="date"
            value-format="x"
            placeholder="选择跟进时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label-width="6em" label="跟进备注" prop="followRemark" style="grid-column: 1 / -1;">
          <el-input
            v-model="formData.followRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入跟进备注"
          />
        </el-form-item>
      </fieldset>

      <fieldset>
        <legend>客户资质</legend>
        <!-- <el-form-item label-width="6em" label="来源" prop="source">
          <el-select v-model="formData.source" placeholder="请选择来源" style="width: 100%">
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_SOURCE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label-width="6em" label="房产情况" prop="realestate">
          <el-select
            v-model="formData.realestate"
            placeholder="请选择房产情况"
            style="width: 100%"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.REALESTATE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label-width="7em" label="公积金情况" prop="housingProvidentFund">
          <el-select
            v-model="formData.housingProvidentFund"
            placeholder="请选择公积金情况"
            style="width: 100%"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.HOUSINGPROVIDENTFUND)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label-width="6em" label="社保情况" prop="socialinsurance">
          <el-select
            v-model="formData.socialinsurance"
            placeholder="请选择社保情况"
            style="width: 100%"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.SOCIALINSURANCE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </fieldset>

      <fieldset>
        <legend>备注信息</legend>
        <el-form-item label-width="8em" label="客户条件备注" prop="remark" style="grid-column: 1 / -1;">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入客户条件备注"
          />
        </el-form-item>
      </fieldset>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { MyCustomerApi, MyCustomer } from '@/api/system/mycustomer'
import { omit } from 'lodash-es'
import { customerApi } from '@/api/system/customer'

/** 标记客户 表单 */
defineOptions({ name: 'MyCustomerForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  username: undefined,
  sex: undefined,
  age: undefined,
  quota: undefined,
  mobile: undefined,
  remark: undefined,
  starRating: undefined,
  realestate: undefined,
  housingProvidentFund: undefined,
  socialinsurance: undefined,
  followTime: undefined,
  followRemark: undefined,
  followUpStatus: undefined,
  followUpFrequency: 0,
})
const formRules = reactive({
  username: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
  quota: [{ required: true, message: '贷款额度不能为空', trigger: 'change' }],
  mobile: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }],
  followUpFrequency: [{ required: true, message: '跟进次数不能为空', trigger: 'change' }],
  followTime: [{ required: true, message: '跟进时间不能为空', trigger: 'change' }],
  followRemark: [{ required: true, message: '跟进备注不能为空', trigger: 'change' }],
  followUpStatus: [{ required: true, message: '跟进状态不能为空', trigger: 'change' }],
  remark: [{ required: true, message: '客户条件备注不能为空', trigger: 'blur' }],
  // source: [{ required: true, message: '来源不能为空', trigger: 'change' }],
  starRating: [{ required: true, message: '客户星级不能为空', trigger: 'change' }],
  realestate: [{ required: true, message: '房产不能为空', trigger: 'change' }],
  housingProvidentFund: [{ required: true, message: '公积金不能为空', trigger: 'change' }],
  socialinsurance: [{ required: true, message: '社保不能为空', trigger: 'change' }],
  // customerType: [{ required: true, message: '客户类型不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

const followUpList = ref([]);
function getFollowUpList() {
  return customerApi.getFollowUpList()
  .then(data => {
    followUpList.value = data;
  });
}
function handleChangeFollowUp() {
  formData.value.followUpName = followUpList
    .value
    .find(
      item => formData.value.followUp == item.id
    )
    ?.username;
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  getFollowUpList();
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MyCustomerApi.getMyCustomer(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = omit(formData.value, ['customerId']) as unknown as MyCustomer
    if (formType.value === 'create') {
      await MyCustomerApi.createMyCustomer(data)
      message.success(t('common.createSuccess'))
    } else {
      await MyCustomerApi.updateMyCustomer(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    username: undefined,
    sex: undefined,
    age: undefined,
    quota: undefined,
    mobile: undefined,
    remark: undefined,
    starRating: undefined,
    realestate: undefined,
    housingProvidentFund: undefined,
    socialinsurance: undefined,
    followTime: undefined,
    followRemark: undefined,
    followUpStatus: undefined,
    followUpFrequency: 0,
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.el-form {
  overflow: auto;
  padding-right: 10px;
  height: 630px;
}

fieldset {
  display: grid;
  gap: 6px 10px;
  grid-template-columns: repeat(4,minmax(0,1fr));
  padding-right: 8px;
  padding-bottom: 4px;
  margin-bottom: 14px;
  border: 1px solid #ccc;
  border-radius: 6px;
}

legend {
  padding-left: 1em;
  padding-right: 1em;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
}
</style>